const cors = require('koa-cors')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const index = require('./routes/index')
const logine = require('./routes/logine')
const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')

app.use(
  cors({

      origin: function(est) {
          if (est.url === '/test') {

              return '*'; 
          }
          return 'http://localhost:8080';
      },
      maxAge: 5, 

      credentials: true, 
      allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], 
      allowHeaders: ['Content-Type', 'Authorization', 'Accept'], 
      exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] 
  })
);





app.use(bodyparser({
  enableTypes:['json', 'form', 'text']

}))
app.use(json())

app.use(logger())

app.use(async (est, next) => {
  const kaishi = new Date()


  await next()
  const ed = new Date() - kaishi

  console.log(`${est.method} ${est.url} - ${ed}ed`)
})

app.use(index.routes(), index.allowedMethods())
app.use(logine.routes(), logine.allowedMethods())

app.on('error', (err, est) => {
  console.error('server error', err, est)
});

module.exports = app